package com.pybox.service;

import com.pybox.common.utils.JdbcTemplateUtils;
import com.pybox.common.utils.ParamUtils;
import com.pybox.dto.Result;
import com.pybox.dto.TCabinetUsersDto;
import com.pybox.dto.TCabinetsDto;
import com.pybox.entity.TCabinets;
import com.pybox.repository.TCabinetsRepository;
import com.pybox.repository.TObjectsCabinetRepository;
import com.pybox.spec.TCabinetsSpec;
import com.pybox.util.CopyUtils;
import com.pybox.util.TimeDealUtils;
import com.pybox.util.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 描述：TCabinets Service
 *
 * @author wuyingkai
 * @date 2018-09-15
 */

@Service
@Transactional
public class TCabinetsService {

    @Autowired
    private TCabinetsRepository repository;

    @Autowired
    private TCabinetUsersService tCabinetUsersService;

    @Autowired
    private TObjectsCabinetRepository tObjectsCabinetRepository;

    @Autowired
    private JdbcTemplateUtils jdbcTemplateUtils;
    /**
     * 创建TCabinets
     *
     * @param source
     * @return
     */
    public boolean create(TCabinetsDto source) {

        TCabinets target = new TCabinets();
        target.setCtime(new Timestamp(System.currentTimeMillis()));
        BeanUtils.copyProperties(source, target);
        repository.save(target);

        TCabinetUsersDto dto =new TCabinetUsersDto();
        dto.setUserId(UserUtils.getUserId());
        dto.setDeleted(0);
        dto.setCabinetId(target.getId());
        dto.setCtime(new Timestamp(System.currentTimeMillis()));
        //新增柜子的人默认具有操作权限
        tCabinetUsersService.create(dto);

        return true;

    }

    /**
     * 根据ID删除TCabinets
     *
     * @param id
     * @return
     */
    public boolean delete(Integer id) {

        repository.delete(id);

        return true;

    }

    /**
     * 更新TCabinets
     *
     * @param id
     * @param source
     * @return
     */
    public boolean update(Integer id, TCabinetsDto source) {

        TCabinets exist = repository.findOne(id);
        if (null == exist) {
            throw new RuntimeException("记录不存在");
        }

        CopyUtils.copyProperties(source, exist);
        exist.setUtime(new Timestamp(System.currentTimeMillis()));
        repository.save(exist);
        return true;

    }

    /**
     * 根据ID查询TCabinets
     *
     * @param id
     * @return
     */
    public TCabinetsDto detail(Integer id) {

        TCabinets exist = repository.findOne(id);
        if (null == exist) {
            throw new RuntimeException("记录不存在");
        }

        //把exist属性赋值给target（相同的属性）
        TCabinetsDto target = new TCabinetsDto();
        BeanUtils.copyProperties(exist, target);
        return target;

    }

    /**
     * 分页查询查询TCabinets
     *
     * @param pageNo
     * @param pageSize
     * @param paramMap
     * @return
     */
    public Page<TCabinetsDto> page(Integer pageNo, Integer pageSize, Map<String, String> paramMap) {

        Pageable pageable = new PageRequest(pageNo - 1, pageSize);
        //当前人的同客户id 的过滤
        String customerId = UserUtils.getCustomerId().toString();
        paramMap.put("customerId",customerId);
        //Page<TCabinets> data = repository.findAll(new TCabinetsSpec(paramMap), pageable);
        List<Object> object =new ArrayList<>();
        String sql = "SELECT c.id,c.name,c.is_online,c.last_update,c.heartbeat_invl,c.uuid,c.utime ,c.customer_id FROM t_cabinets c where 1 = 1";
        String where =  new ParamUtils().getTCabinetsParams(paramMap,sql);
        Page<TCabinets> data = jdbcTemplateUtils.page(where,object,TCabinets.class,pageNo,pageSize);
        List<TCabinetsDto> list = new ArrayList<>();
        Integer objectCount =0;
        for (TCabinets obj : data.getContent()) {
            objectCount=tObjectsCabinetRepository.getObjectCountByCabinetUUID(obj.getUuid());
            TCabinetsDto dto = new TCabinetsDto();
            //把exist属性赋值给target（相同的属性）
            BeanUtils.copyProperties(obj, dto);
            dto.setObjectCount(objectCount);
            list.add(dto);
        }

        Page<TCabinetsDto> page = new PageImpl<>(list, pageable, data.getTotalElements());

        return page;
    }

    //根据uuid查询物品柜
    public TCabinetsDto getDetailByUUID(String uuid) {
        TCabinets t = repository.findTCabinetsByUuid(uuid);
        TCabinetsDto td = new TCabinetsDto();
        if (null == t) {
            return null;
        }
        BeanUtils.copyProperties(t, td);
        return td;
    }
    public Result<Boolean> checkCabinetPasswordUnique( String password){
        boolean exist =false;
        Integer customerId = UserUtils.getCurrentUser().getCustomerId();
        int count = repository.checkCabinetPasswordUnique(password,customerId);
        if (count > 0 ){
            exist =true;
        }
        return Result.ok(exist);
    }
}